<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="新增下游订单"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 60px);" :show-scrollbar="false">
			<view style=" background-color:#EFEDE9;">
				<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
			</view>
			<view class="pl-3 pr-2">
				<u-form :model="form" ref="uForm">
					
					<!-- <u-form-item required label-width="180" label="下游服务商" prop="productInformId">
						<u-input v-model="valueProductName" placeholder="请选择下游服务商" :type="type" input-align="right"
							:border="false" @click="showProductName = true" />
						<u-action-sheet :list="actionListCp" v-model="showProductName"
							@click="actionClickProductName"></u-action-sheet>
					</u-form-item> -->
					<u-form-item  required label-width="180" label="下游服务商"
						prop="productInformId">
						<u-input v-model="valueProductName" placeholder="请选择下游服务商" :type="type"
							input-align="right" :border="false" @click="showNatureBusinessHandler" />
						<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
							:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
					</u-form-item>

					<u-form-item required label-width="180" label="需求标题" prop="title">
						<u-input class="mr-3 " v-model="form.title" placeholder="请输入需求标题" input-align="right" />
					</u-form-item>

				<!-- 	<u-form-item required label-width="180" label="产品名称" prop="name">
						<u-input v-model="valueProductNameList" placeholder="请选择产品名称" :type="type" input-align="right"
							:border="false" @click="showProductNameList = true" />
						<u-action-sheet :list="actionListCpList" v-model="showProductNameList"
							@click="actionClickProductNameList"></u-action-sheet>
					</u-form-item> -->
					<u-form-item  required label-width="180" label="产品名称"
						prop="productInformId">
						<u-input v-model="valueProductNameList" placeholder="请选择产品名称"  :type="type"
							input-align="right" :border="false" @click="valueListCpHandler" />
						<u-picker @confirm="selectValueListCp" mode="selector" v-model="selectValueListCpBusiness"
							:default-selector="[0]" :range="valueListCpBusinessList" range-key="text"></u-picker>
					</u-form-item>
					
					<u-form-item required label-width="180" label="联系人" prop="legalRepresentative">
						<u-input class="mr-3 " v-model="userInfo.legalRepresentative" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="180" label="联系方式" prop="phone">
						<u-input class="mr-3 " v-model="userInfo.phone" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="180" label="数量" prop="number">
						<u-input class="mr-3 " v-model="form.number"  placeholder="请输入数量" input-align="right" />
						<text class="mr-3 ">{{form.productSpecsText}}</text>
					</u-form-item>
					<u-form-item required label-width="180" label="价格(元)" prop="price">
						<u-input class="mr-3 " v-model="form.price" placeholder="请输入价格" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="180" label="截止日期" prop="name">
						<uni-calendar ref="calendarl" :start-date="currentDate" :insert="false" :lunar="true" @confirm="confirmName" />
						<view v-if="!selectedNameDate" class="text-999999 right-1-5 position-absolute"
							@click="openName">
							请选择日期</view>
						<view class="right-1-5 position-absolute" @click="openName">{{ formattedEndTime }}</view>
					</u-form-item>

					<view style=" background-color:#EFEDE9;">
						<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">我的信息</view>
					</view>
					<u-form-item  v-if="userInfo.parentId === null" required label-width="180" label="涉农企业" prop="agricultureUserId">
						<u-input  :disabled="true" v-model="userInfo.enterpriseName"
							input-align="right" />
					</u-form-item>
					<u-form-item v-else required label-width="180" label="涉农企业" prop="agricultureUserId">
						<u-input  :disabled="true" v-model="userInfo.parentEnterpriseName"
							input-align="right" />
					</u-form-item>
					<u-form-item required label-width="180" label="联系方式" prop="name">
						<u-input class="mr-3" :disabled="true" v-model="userInfo.phone" input-align="right" />
					</u-form-item>
					<view style=" background-color:#EFEDE9;">
						<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">订单信息</view>
					</view>
					<u-form-item required label-width="180" label="订单时间" prop="name">
						<uni-calendar ref="calendars" :start-date="currentDate" :insert="false" :lunar="true" @confirm="confirmList" />
						<view v-if="!selectedListDate" class="text-999999 right-1-5 position-absolute"
							@click="openList">
							请选择日期</view>
						<view v-else class="right-1-5 position-absolute" @click="openList()">{{ formattedOrderTime}}</view>
					</u-form-item>
					<u-form-item required label-width="180" label="订单进度" prop="orderSchedule">
						<u-input class="mr-3" v-model="form.orderSchedule" placeholder="请输入订单进度" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="180" label="订单评价" prop="orderEvaluation">
						<u-input class="mr-3" v-model="form.orderEvaluation" placeholder="请输入订单评价" input-align="right" />
					</u-form-item>
				</u-form>
			</view>
			<ferrButton title="新增下游订单" @click="submit"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	export default {
		components: {
			ferrButton,
			calendar
		},
		data() {
			return {
				form: {
					downUserId: '',
					title: '',
					productName: '',
					downLegalRepresentative: '',
					downPhone: '',
					number: '',
					price: '',
					orderEvaluation: '',
					endTime: '',
					orderTime: '',
					orderSchedule: '',
					productSpecs: '',
					productSpecsText:''
				},
				value: '',
				valueList: '',

				type: 'select',
				showData: false,
				selectedDate: null,
				selectedNameDate: null,
				selectedListDate: null,
				show: false,
				showList: false,

				// 下游订单
				selectedDate: null,
				selectedNameDate: null,
				actionListCp: [], // 产品名称列表
				showProductName: false, // 控制显示产品名称选项的变量
				
				list: {
					userType: 'DOWN_SERVICE',
				},
				// 产品名称
				
				showProductNameList: false,
				actionListCpList: [],
				userInfo: null,
				border: true,
				rules: {
					title: [{
						required: true,
						message: '需求标题不能为空',
						trigger: ['change', 'blur'],
					}],
					number: [{
						validator: (rule, value, callback) => {
							if (!value) {
								callback(new Error('数量不能为空'));
							} else {
								const reg = /^[0-9]+(\.[0-9]+)?$/; // 只允许输入数字
								if (!reg.test(value)) {
									callback(new Error('请输入数字'));
								} else {
									callback();
								}
							}
						},
						trigger: ['change', 'blur'],
					}],
					price: [{
						validator: (rule, value, callback) => {
							if (!value) {
								callback(new Error('价格不能为空'));
							} else {
								const reg = /^[0-9]+(\.[0-9]+)?$/; // 只允许输入数字
								if (!reg.test(value)) {
									callback(new Error('请输入数字'));
								} else {
									callback();
								}
							}
						},
						trigger: ['change', 'blur'],
					}],
					orderSchedule: [{
						required: true,
						message: '订单进度不能为空',
						trigger: ['change', 'blur'],
					}],
					orderEvaluation: [{
						required: true,
						message: '订单评价不能为空',
						trigger: ['change', 'blur'],
					}],
				},
				pages: {
				  pageNo: 1,
				  pageSize: 100,
				  total: 0, 
				},
              
			  valueProductName: '',
			  showNatureBusiness: false,
			  natureBusinessList: [],
			  
			  valueProductNameList: '',
			  valueListCpBusinessList: [],
			  selectValueListCpBusiness: false,
			  
			};
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.userInfo = userInfo;
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'none',
				});
			}
			this.NewListD();
			this.NameList()
		},
		created() {
			this.setCurrentDate();
		},
		computed: {
			formattedOrderTime() {
				if (!this.form.orderTime) return '';
				return this.form.orderTime.split(' ')[0];
			},
			formattedEndTime() {
				if (!this.form.endTime) return '';
				return this.form.endTime.split(' ')[0];
			}
		},
		methods: {
			// 下游服务商
			showNatureBusinessHandler() {
				this.showNatureBusiness = true;
			},
			selectNatureBusiness(e) {
				this.valueProductName = this.natureBusinessList[e[0]].text;
				this.form.downUserId =this.natureBusinessList[e[0]].id;
			},
			NewListD() {
				const requestData = {
					...this.list,
					...this.pages
				};
				$H.get('/brand/user/selectUserList', requestData, {}).then((res) => {
					this.natureBusinessList = (res.result || []).map((v) => {
						return {
							text: v.enterpriseName,
							id: v.id
						}
					})
					const target = this.natureBusinessList.find(
						(v) => v.id === this.form.downUserId
					)
					this.valueProductName = target ? target.text : ''
				})
			},
			// actionClickProductName(index) {
			// 	this.valueProductName = this.actionListCp[index].text;
			// 	// this.form.productInformId = this.actionListCp[index].id
			// 	// this.form.agricultureUserId = this.actionListCp[index].id;
			// 	this.form.downUserId = this.actionListCp[index].id;
			// 	// this.form.upperMarketProductId = this.actionListCp[index].id;
			// },

			// 产品名称
			valueListCpHandler() {
				this.selectValueListCpBusiness = true;
			},
			selectValueListCp(e) {
				this.valueProductNameList = this.valueListCpBusinessList[e[0]].text;
				this.form.productNameId = this.valueListCpBusinessList[e[0]].id;
				this.form.productSpecs = this.valueListCpBusinessList[e[0]].productSpecs;
				this.form.productSpecsText = this.valueListCpBusinessList[e[0]].productSpecsText
			},
			NameList() {
				$H.get('/basisInform/productName/list', {...this.pages

				}).then((res) => {
					this.valueListCpBusinessList = (res.result.records || []).map((v) => {
						return {
							text: v.productName,
							id: v.id,
							productSpecs: v.productSpecs,
							productSpecsText: v.productSpecsText
						}
					})
					const target = this.valueListCpBusinessList.find(
						(v) => v.id === this.form.productNameId
					)
					this.valueProductNameList = target ? target.text : ''
				})
			},
			// actionClickProductNameList(index) {
			// 	this.valueProductNameList = this.actionListCpList[index].text;
			// 	this.form.productNameId = this.actionListCpList[index].id;
			// 	this.form.productSpecs = this.actionListCpList[index].productSpecs;
			// },

			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (this.form.orderTime) {
							const date = new Date(this.form.orderTime);
							this.form.orderTime =
								`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} 00:00:00`;
						}
						if (this.form.endTime) {
							const date = new Date(this.form.endTime);
							this.form.endTime =
								`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} 00:00:00`;
						}
						const requestData = {
							...this.form,
							agricultureUserId: this.userInfo.enterpriseName,
							phone: this.userInfo.phone
						};
						$H.post('/down/downServiceOrder/agriculture/addOrder', requestData, {}).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: res.message || '新增成功',
									icon: 'success',
									duration:4000
								})
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 4000);
							} else {
								uni.showToast({
									title: res.message || '新增失败',
									icon: 'none',
								})
							}
						}).catch(error => {
							uni.showToast({
								title: "网络错误，请稍后再试",
								icon: 'none'
							});
						});
					} else {
						uni.showToast({
							title: "请完整填写表单",
							icon: 'none'
						});
					}
				});
			},
			// 下游订单
			openName() {
				this.$refs.calendarl.open();
			},
			confirmName(e) {
				this.selectedNameDate = e.fulldate;
				// 获取当前的日期
				const formattedDate = e.fulldate; // 只使用日期部分
				this.form.endTime = formattedDate;
			
			},
			setCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份补齐两位数
				const day = now.getDate().toString().padStart(2, '0'); // 日期补齐两位数
				this.currentDate = `${year}-${month}-${day}`;
			},
			openList() {
				this.$refs.calendars.open();
			},
			confirmList(e) {
				this.selectedListDate = e.fulldate;		
				const formattedDate = e.fulldate; // 只使用日期部分
				this.form.orderTime = formattedDate;
			},
		},
	};
</script>
</script>

<style>
</style>